<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px"
      style="width: 80%; margin-left: 50px" :disabled="dialogStatus == 'look'">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="数据源名称" prop="name">
            <el-input v-model="temp.name" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据源类型" prop="dbType">
            <el-select v-model="temp.dbType" class="filter-item" placeholder="请选择数据源类型" @change="choseType">
              <el-option v-for="item in dictList('datasource_type')" :key="'type' + item.label" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="temp.dbType === '9'">
          <el-form-item label="mysql链接" prop="mysqlUrl">
            <el-input v-model="temp.dbSchema.mysqlUrl" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio v-for="item in dictList('is_use')" :key="'type' + item.label" v-model="temp.status"
              :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主机" prop="dbSchema.host">
            <el-input v-model="temp.dbSchema.host" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="端口号" prop="dbSchema.port">
            <el-input v-model="temp.dbSchema.port" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="temp.dbType != '3' && temp.dbType != '4'">
          <el-form-item label="数据库" prop="dbSchema.dbName">
            <el-input v-model="temp.dbSchema.dbName" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="temp.dbType == '3' || temp.dbType == '4'">
          <el-form-item label="连接方式" prop="dbSchema.connectType">
            <el-select v-model="temp.dbSchema.connectType" class="filter-item" placeholder="请选择连接方式"
              @change="choseContectType">
              <el-option v-for="item in dictList('oracle_conType')" :key="'type' + item.label" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="temp.dbType == '12' || temp.dbType == '6'">
          <el-form-item label="模式名" prop="dbSchema.schemaName">
            <el-input v-model="temp.dbSchema.schemaName" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="temp.dbType == '3' || temp.dbType == '4'">
          <el-form-item label="sid" prop="dbSchema.sid" v-if="temp.dbSchema.connectType == '1'">
            <el-input v-model="temp.dbSchema.sid" />
          </el-form-item>
          <el-form-item label="服务名" prop="dbSchema.dbName" v-if="temp.dbSchema.connectType == '0'">
            <el-input v-model="temp.dbSchema.dbName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名" prop="dbSchema.username">
            <el-input v-model="temp.dbSchema.username" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="dbSchema.password">
            <el-input v-model="temp.dbSchema.password" :type="passwordType" />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="其所在目录" prop="directoryId">
            <el-cascader v-model="temp.directoryId" :options="options" :props="treeProps" :show-all-levels="false"
              label="label" change-on-select clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="dialogStatus != 'look'" :loading="loading" @click="testLinkbtn"> 测试连通性
      </el-button>
      <el-button @click="dialogFormVisible = false">
        {{ $t('table.cancel') }}
      </el-button>
      <el-button type="primary" :loading="loading" v-if="dialogStatus != 'look'"
        @click="dialogStatus === 'create' ? createData() : updateData()">
        {{ $t('table.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createsource, updatesource, getsource, testLink } from '@/api/metadata/source/source'
import { fetchMasterdataDirectoryList } from '../../../api/masterdata/masterdataDirectory'

export default {
  name: 'sourceForm',
  data() {
    return {
      rules: {
        name: [{ required: true, message: '数据源名称为必填项', trigger: 'blur' }],
        dbType: [{ required: true, message: '数据源类型为必填项', trigger: 'blur' }],
        status: [{ required: true, message: '状态为必填项', trigger: 'blur' }],
        'dbSchema.mysqlUrl': [{ required: true, message: 'mysql连接串为必填项', trigger: 'blur' }],
        'dbSchema.host': [{ required: true, message: '主机为必填项', trigger: 'blur' }],
        'dbSchema.port': [{ required: true, message: '端口号为必填项', trigger: 'blur' }],
        'dbSchema.dbName': [{ required: true, message: '数据库为必填项', trigger: 'blur' }],
        'dbSchema.username': [{ required: true, message: '用户名为必填项', trigger: 'blur' }],
        'dbSchema.password': [{ required: true, message: '密码为必填项', trigger: 'blur' }],
        'dbSchema.sid': [{ required: true, message: 'sid为必填项', trigger: 'blur' }],
        'dbSchema.schemaName': [{ required: true, message: '模式名为必填项', trigger: 'blur' }],
        'dbSchema.connectType': [{ required: true, message: '连接方式为必填项', trigger: 'blur' }],
        directoryId: [{ required: true, message: '目录为必填项', trigger: 'blur' }],
      },
      treeProps: {
        value: 'id',
        label: 'name',
        emitPath: false,
      },
      temp: {
        name: '',
        dbType: '',
        status: '',

        directoryId: '',
        dbSchema: {
          schemaName: '',
          host: '',
          port: '',
          dbName: '',
          username: '',
          password: '',
          sid: '',
          connectType: '',
          mysqlUrl: '',
        },
      },
      textMap: {
        update: '编辑',
        create: '新建',
      },
      options: [],
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      passwordType: 'password',
    }
  },

  methods: {
    fun() {
      fetchMasterdataDirectoryList({
        page: 1,
        limit: 25,
        ancestralId: 3,
      }).then((res) => {
        this.options = res.data.data
      })
    },
    choseContectType(val) {
      if (val == 0) {
        this.rules['dbSchema.dbName'][0].required = true
        this.temp.dbSchema.sid = ''
      } else if (val == 1) {
        this.rules['dbSchema.dbName'][0].required = false
        this.temp.dbSchema.dbName = ''
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    choseType(val) {
      if (val == 3 || val == 4) {
        this.rules['dbSchema.sid'][0].required = true

        this.rules['dbSchema.connectType'][0].required = true
      } else if (val == 15) {

        this.rules['dbSchema.password'][0].required = false
      } else {
        this.rules['dbSchema.sid'][0].required = false
        this.rules['dbSchema.connectType'][0].required = false
      }
    },
    getList() {
      this.$emit('refreshList')
    },
    resetTemp() {
      this.loading = false
      this.temp = {
        id: undefined,
        name: undefined,
        createBy: undefined,
        createTime: undefined,
        createDept: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remarks: undefined,
        dbType: undefined,
        status: undefined,
        isSync: undefined,

        directoryId: '',
        dbSchema: {
          schemaName: undefined,
          host: undefined,
          port: undefined,
          dbName: undefined,
          username: undefined,
          password: undefined,
          sid: '',
          connectType: '',
          mysqlUrl: '',
        },
      }
    },
    handleCreate(directoryId) {
      this.fun()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.temp.directoryId = directoryId
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    testLinkbtn() {
      this.temp = {
        id: this.temp.id,
        name: this.temp.name,
        createBy: this.temp.createBy,
        createTime: this.temp.createTime,
        createDept: this.temp.createDept,
        updateBy: this.temp.updateBy,
        updateTime: this.temp.updateTime,
        remarks: this.temp.remarks,
        dbType: this.temp.dbType,
        status: this.temp.status,
        isSync: this.temp.isSync,
        directoryId: this.temp.directoryId,
        dbSchema: {
          host: this.temp.dbSchema.host,
          schemaName: this.temp.dbSchema.schemaName,
          port: this.temp.dbSchema.port,
          dbName: this.temp.dbSchema.dbName,
          username: this.temp.dbSchema.username,
          password: this.temp.dbSchema.password,
          sid: this.temp.dbSchema.sid,
          connectType: this.temp.dbSchema.connectType,
          mysqlUrl: this.temp.dbSchema.mysqlUrl,
        },
      }
      testLink(this.temp)
        .then((res) => {
          if (res.data.code === 0) {
            this.getList()
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((err) => {
          this.$message.error('测试连通失败，请检查您的参数')
        })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          createsource(this.temp)
            .then((response) => {
              this.loading = false
              if (response.data.code === 0) {
                this.getList()
                this.dialogFormVisible = false
                this.$message.success(response.data.msg)
              } else {
                this.$message.error(response.data.msg)
              }
            })
            .catch((err) => {
              this.$message.error('该数据源信息已经存在！')
            })
        }
      })
    },
    handleUpdate(id) {
      this.fun()
      this.resetTemp()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      getsource(id).then((response) => {
        if (response.data.code === 0) {
          let val = this.getParentsById(this.options, response.data.data.directoryId)
          this.temp = {
            id: response.data.data.id,
            name: response.data.data.name,
            createBy: response.data.data.createBy,
            createTime: response.data.data.createTime,
            createDept: response.data.data.createDept,
            updateBy: response.data.data.updateBy,
            updateTime: response.data.data.updateTime,
            remarks: response.data.data.remarks,
            dbType: response.data.data.dbType,
            status: response.data.data.status,
            isSync: response.data.data.isSync,
            directoryId: response.data.data.directoryId,
            dbSchema: {
              schemaName: this.temp.dbSchema.schemaName,

              host: response.data.data.dbSchema.host,
              port: response.data.data.dbSchema.port,
              dbName: response.data.data.dbSchema.dbName,
              username: response.data.data.dbSchema.username,
              password: response.data.data.dbSchema.password,
              sid: response.data.data.dbSchema.sid,
              connectType: response.data.data.dbSchema.connectType,
              mysqlUrl: response.data.data.dbSchema.mysqlUrl,
            },
          }
        } else {
          this.dialogFormVisible = false
          this.$message.error(response.data.msg)
        }
      })
    },
    getParentsById(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          //这里的list[i].id中的id根据你的需求可进行改变
          //查询到就返回该数组对象的value
          return [list[i].id]
        }
        if (list[i].children) {
          let node = this.getParentsById(list[i].children, id)
          if (node !== undefined) {
            //查询到把父节把父节点加到数组前面
            node.unshift(list[i].id)
            return node
          }
        }
      }
    },
    handleLook(id) {
      this.resetTemp()
      this.dialogStatus = 'look'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      getsource(id).then((response) => {
        if (response.data.code === 0) {
          this.temp = response.data.data
        } else {
          this.dialogFormVisible = false
          this.$message.error(response.data.msg)
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true

          this.temp = {
            id: this.temp.id,
            name: this.temp.name,
            createBy: this.temp.createBy,
            createTime: this.temp.createTime,
            createDept: this.temp.createDept,
            updateBy: this.temp.updateBy,
            updateTime: this.temp.updateTime,
            remarks: this.temp.remarks,
            dbType: this.temp.dbType,
            status: this.temp.status,
            isSync: this.temp.isSync,

            directoryId: this.temp.directoryId,
            dbSchema: {
              schemaName: this.temp.dbSchema.schemaName,

              host: this.temp.dbSchema.host,
              port: this.temp.dbSchema.port,
              dbName: this.temp.dbSchema.dbName,
              username: this.temp.dbSchema.username,
              password: this.temp.dbSchema.password,
              sid: this.temp.dbSchema.sid,
              connectType: this.temp.dbSchema.connectType,

              mysqlUrl: this.temp.dbSchema.mysqlUrl,
            },
          }

          updatesource(this.temp)
            .then((response) => {
              this.loading = false
              if (response.data.code === 0) {
                this.dialogFormVisible = false
                this.getList()
                this.$message.success(response.data.msg)
              } else {
                this.$message.error(response.data.msg)
              }
            })
            .catch((err) => {
              this.$message.error('该数据源信息已经存在！')
              this.loading = false
            })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.show-pwd {
  position: absolute;
  right: 10px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}

.el-cascader--medium {
  width: 100%;
}
</style>
